<template>
  <basic-container>
    <avue-crud v-bind="bindVal"
               v-on="onEvent"
               v-model="form"
               :before-open="beforeOpen"
               ref="crud">

      <template slot="menuLeft">
        <el-button type="danger"
                   v-if="validatenull(permission.delCodeShow)?false:permission.delCodeShow"
                   icon="el-icon-delete"
                   size="small"
                   @click.stop="deletes()">批量删除
        </el-button>
      </template>

      <template slot="menu"
                slot-scope="scope">

        <el-button type="text"
                   size="small"
                   v-if="validatenull(permission.roleUserCodeShow)?false:permission.roleUserCodeShow"
                   icon="el-icon-user"
                   @click="handleUser(scope.row,scope.index)">角色成员
        </el-button>

        <el-button type="text"
                   size="small"
                   v-if="validatenull(permission.setAuthCodeShow)?false:permission.setAuthCodeShow"
                   icon="el-icon-setting"
                   @click="handleRole(scope.row,scope.index)">功能权限
        </el-button>
        <el-button type="text"
                   size="small"
                   v-if="validatenull(permission.setDataAuthCodeShow)?false:permission.setDataAuthCodeShow"
                   icon="el-icon-setting"
                   @click="handleData(scope.row,scope.index)">数据权限
        </el-button>
      </template>

    </avue-crud>

    <el-drawer
        :title="`[${roleUserName}] 角色成员`"
        append-to-body
        size="1000px"
        :visible.sync="userBox">

      <basic-container>
        <avue-crud :option="optionUser"
                   :data="dataUser"
                   :page.sync="pageUser"
                   :table-loading="userLoading"
                   :search.sync="searchUser"
                   ref="tableUser"
                   @search-change="searchChangeUser"
                   @search-reset="searchResetUser"
                   @current-change="currentChangeUser"
                   @size-change="sizeChangeUser">

          <template slot="menuLeft">
            <el-button v-if="permission.addUserCodeShow===undefined?false:permission.addUserCodeShow" icon="el-icon-plus" type="primary" size="small" @click.stop="roleUser()">添加</el-button>
            <el-button v-if="permission.delUserCodeShow===undefined?false:permission.delUserCodeShow" icon="el-icon-delete" type="danger" size="small" @click.stop="deleteUser()" :loading="deleteUserLoading">去除</el-button>
          </template>

          <template slot-scope="{disabled,size}" slot="userTypeStrSearch">
            <avue-select v-model="searchUser.userType_eq" placeholder="请选择用户类型" :disabled="disabled" :size="size" type="tree" :props="{label: 'name',value: 'code'}" :dic="userTypeList"></avue-select>
          </template>
          <template slot-scope="{disabled,size}" slot="orgNameSearch">
            <avue-input-tree v-model="searchUser.orgId_eq" placeholder="请选择部门" :disabled="disabled" :size="size" type="tree" :props="{label: 'title',value: 'id'}" :dic="orgList"></avue-input-tree>
          </template>

        </avue-crud>
      </basic-container>

    </el-drawer>

    <el-dialog class="avue-dialog chilentTable" title="添加成员"
               top="20px"
               append-to-body
               :visible.sync="roleUserBox">

      <avue-crud :option="optionRoleUser"
                 :data="dataRoleUser"
                 :page="pageRoleUser"
                 :table-loading="roleUserLoading"
                 :search.sync="searchRoleUser"
                 ref="tableRoleUser"
                 @search-change="searchChangeRoleUser"
                 @search-reset="searchResetRoleUser"
                 @current-change="currentChangeRoleUser"
                 @size-change="sizeChangeRoleUser">

        <template slot-scope="{disabled,size}" slot="userTypeStrSearch">
          <avue-select v-model="searchRoleUser.userType_eq" placeholder="请选择用户类型" :disabled="disabled" :size="size" type="tree" :props="{label: 'name',value: 'code'}" :dic="userTypeList"></avue-select>
        </template>
        <template slot-scope="{disabled,size}" slot="orgNameSearch">
          <avue-input-tree v-model="searchRoleUser.orgId_eq" placeholder="请选择部门" :disabled="disabled" :size="size" type="tree" :props="{label: 'title',value: 'id'}" :dic="orgList"></avue-input-tree>
        </template>

      </avue-crud>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="roleUserBox = false">取 消</el-button>
        <el-button type="primary" :loading="addUserLoading"
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog class="avue-dialog" title="配置功能权限"
               append-to-body
               :visible.sync="box">
      <el-container>
        <el-aside width="200px">
          <p class="el-dialog__title">菜单</p>
          <el-tree :data="menuGrantList"
                   node-key="id"
                   ref="treeMenu"
                   style="max-height: 450px;"
                   show-checkbox
                   defaultExpandAll
                   checkStrictly
                   :expandOnClickNode="false"
                   :default-checked-keys="functionIds"
                   :props="{label: 'title',value: 'id'}"
                   @check-change="checkChange"
                   @node-click="listFunction">
          </el-tree>
        </el-aside>
        <el-main class="chilentTable">
          <p class="el-dialog__title">接口、按钮</p>
          <avue-crud ref="functionTable" :data="functionList" :option="optionFunction" @selection-change="functionSelectionChange" ></avue-crud>
        </el-main>
      </el-container>


      <span slot="footer"
            class="dialog-footer">
        <el-button @click="box = false">取 消</el-button>
        <el-button type="primary"
                   @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog class="avue-dialog" title="配置数据权限"
               append-to-body
               :visible.sync="databox">

      <el-container>
        <el-aside width="200px">
          <p class="el-dialog__title">菜单</p>
          <el-tree :data="menuData"
                   node-key="id"
                   ref="treeData"
                   style="max-height: 450px;"
                   defaultExpandAll
                   :expandOnClickNode="false"
                   :props="{label: 'title',value: 'id'}"
                   @node-click="listDataScope">
          </el-tree>
        </el-aside>
        <el-main class="chilentTable">
          <p class="el-dialog__title">数据权限</p>
          <avue-crud ref="dataScopeTable" :data="scopedList" :option="optionScope" @current-row-change="currentRowChange" @row-click="rowClick" ></avue-crud>
        </el-main>
      </el-container>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="databox = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitDataScope">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { menuTree } from '@/api/system/menuList'
import { queryUrlIdByRole, addFunction, listByMenuId, listIdByRoleId, roleDataScope,listByRole,addRoleUser,deleteRoleUser,listButByMenu } from '@/api/system/roleTree'
import request from '@/router/axios';

export default window.$crudCommon({
  data () {
    return {
      form: {},
      selectDataId: '',
      box: false,
      databox: false,
      userBox: false,
      roleUserBox: false,
      roleUserName: '',
      dataIds: [],
      list: [],
      scopedList: [],
      menuGrantList: [],
      functionIds: [],
      menuData: [],
      userTypeList: [],
      orgList: [],
      functionList: [],
      optionFunction: {
        index: true,
        indexLabel: '序号',
        selection: true,
        tip: true,
        searchShow: false,
        menu: false,
        border: true,
        columnBtn: false,
        addBtn: false,
        refreshBtn: false,
        align: 'center',
        maxHeight: 450,
        rowKey: 'id',
        column: [
          {
            label: "功能名称",
            prop: "functionName"
          },
          {
            label: "别名",
            prop: "alias"
          },
          {
            label: "编码",
            prop: "code"
          },
          {
            label: "路由",
            prop: "url"
          }
        ]
      },
      optionScope: {
        index: true,
        indexLabel: '序号',
        tip: false,
        searchShow: false,
        menu: false,
        border: true,
        columnBtn: false,
        addBtn: false,
        refreshBtn: false,
        align: 'center',
        maxHeight: 450,
        rowKey: 'id',
        highlightCurrentRow: true,
        column: [
          {
            label: "权限编号",
            prop: "scopeCode"
          },
          {
            label: "数据权限名称",
            prop: "scopeName"
          },
          {
            label: "是否所有角色都执行",
            prop: "allRole",
            type: "switch",
            dicUrl: window.urllist.dictUrl + 'YN01',
            dataType: 'number',
            props: {
              label: "name",
              value: "code"
            }
          }
        ]
      },
      optionUser: {
        index: true,
        indexLabel: '序号',
        selection: true,
        tip: true,
        searchShow: true,
        menu: false,
        border: true,
        addBtnText: "添加",
        columnBtn: false,
        addBtn: false,
        refreshBtn: false,
        searchIcon: true,
        align: 'center',
        maxHeight: 800,
        rowKey: 'id',
        reserveSelection: true,
        column: [
          {
            label: "用户名",
            prop: "loginId",
            search: true
          },
          {
            label: '用户昵称',
            prop: 'nickName',
            search: true
          },
          {
            label: "部门",
            prop: "orgName",
            overHidden: true,
            searchslot:true,
            search: true
          },
          {
            label: "用户类型",
            prop: "userTypeStr",
            searchslot:true,
            search: true
          },
          {
            label: "用户姓名",
            prop: "userName",
            overHidden: true,
            search: true
          },
          {
            label: "电话",
            prop: "telephone",
            overHidden: true
          }
        ]
      },
      dataUser: [],
      pageUser: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      searchUser: {},
      userLoading: true,
      tenantCode: '',
      roleId: '',
      optionRoleUser: {
        index: true,
        indexLabel: '序号',
        selection: true,
        tip: true,
        searchShow: true,
        menu: false,
        border: true,
        addBtnText: "添加",
        columnBtn: false,
        addBtn: false,
        refreshBtn: false,
        searchIcon: true,
        align: 'center',
        maxHeight: 450,
        rowKey: 'id',
        reserveSelection: true,
        column: [
          {
            label: "用户名",
            prop: "loginId",
            search: true
          },
          {
            label: '用户昵称',
            prop: 'nickName',
            search: true
          },
          {
            label: "部门",
            prop: "orgName",
            overHidden: true,
            searchslot:true,
            search: true
          },
          {
            label: "用户类型",
            prop: "userTypeStr",
            searchslot:true,
            search: true
          },
          {
            label: "用户姓名",
            prop: "userName",
            overHidden: true,
            search: true
          },
          {
            label: "电话",
            prop: "telephone",
            overHidden: true
          }
        ]
      },
      dataRoleUser: [],
      pageRoleUser: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      searchRoleUser: {},
      roleUserLoading: true,
      addUserLoading: false,
      deleteUserLoading: false,
      isChange: false
    }
  },
  created () {
    request.get(window.urllist.dictUrl + 'USER_TYPE').then((res) => {
      this.userTypeList = res.data.data;
    })

  },
  methods: {
    currentRowChange(row,oldRow){
      if (row){
        if (!this.dataIds.includes(row.id)){
          this.dataIds.push(row.id);
        }
      }else {
        const index = this.dataIds.indexOf(oldRow.id);
        if (index >= 0){
          this.dataIds.splice(index,1);
        }
      }
    },
    rowClick(row){
      if (this.selectDataId === row.id){
        this.$refs.dataScopeTable.setCurrentRow();
        this.selectDataId = '';
        return;
      }
      this.selectDataId = row.id;
    },
    listDataScope (data) {

      listByMenuId({
        menuId: data.id
      }).then(res => {
        this.scopedList = res.data.data;

        this.selectDataId = '';
        this.dataIds.forEach(ele => {
          this.scopedList.forEach(e => {
            if (ele === e.id) {
              this.selectDataId = ele;
              this.$refs.dataScopeTable.setCurrentRow(e);
            }
          })
        });

      })
    },
    submitDataScope () {
      roleDataScope({
        roleId: this.roleId,
        dataIds: this.dataIds.join(',')
      }).then(() => {
        this.databox = false;
        this.$message({
          type: "success",
          message: "操作成功"
        });
      });
    },
    checkChange(data,select){

      if (select === true){
        if (!this.functionIds.includes(data.id)){
          this.functionIds.push(data.id)
        }
      }else {
        const index = this.functionIds.indexOf(data.id);
        if (index >= 0){
          this.functionIds.splice(index,1);
        }
      }
    },
    functionSelectionChange(selection){
      if (this.isChange){
        this.functionList.forEach(e => {
          const index = this.functionIds.indexOf(e.id);
          if (index >= 0){
            this.functionIds.splice(index,1);
          }
        });

        selection.forEach(e => {
          if (!this.functionIds.includes(e.id)){
            this.functionIds.push(e.id)
          }
        });
      }
    },
    listFunction(data = {}){
      listButByMenu({ id: data.id }).then((res)=>{
        this.isChange=false;// 标记这时不要去更新选中的数据
        this.functionList = res.data.data;

        this.$nextTick(() => {

          const selectFunction = [];
          this.functionIds.forEach(ele => {
            this.functionList.forEach(e => {
              if (ele === e.id) {
                selectFunction.push(e);
              }
            })
          });

          this.$refs.functionTable.toggleSelection(selectFunction);
          this.isChange=true;
        });
      });
    },
    submit () {
      addFunction({
        roleId: this.roleId,
        functionIds: this.functionIds
      }).then(() => {
        this.box = false;
        this.$message({
          type: "success",
          message: "操作成功"
        });
      });
    },
    handleData (row) {
      this.roleId = row.id;
      this.scopedList = [];
      this.selectDataId = '';

      //查询菜单
      menuTree().then(res => {
        this.menuData = res.data.data;
        this.databox = true;
      });

      //查询该角色所拥有的数据权限
      listIdByRoleId({ roleIds: row.id }).then(result => {
        this.dataIds = result.data.data;
      });

    },
    handleRole (row) {
      this.roleId = row.id;
      this.functionIds=[];

      //查询菜单
      menuTree().then(res => {
        this.menuGrantList = res.data.data;
        this.box = true;
      });

      queryUrlIdByRole({
        roleIds: row.id
      }).then(res => {
        this.functionIds = res.data.data;
        this.listFunction();
      });

    },
    searchChangeUser (params, done) {
      this.pageUser.currentPage = 1;
      this.onLoadUser(this.pageUser, params);
      done();
    },
    searchResetUser () {
      this.pageUser.currentPage = 1;
      this.onLoadUser(this.pageUser);
    },
    currentChangeUser(currentPage) {
      this.pageUser.currentPage = currentPage;
      this.onLoadUser(this.pageUser,this.searchUser);
    },
    sizeChangeUser (pageSize) {
      this.pageUser.pageSize = pageSize;
      this.pageUser.currentPage = 1;
      this.onLoadUser(this.pageUser,this.searchUser);
    },
    handleUser (row) {
      this.tenantCode = row.tenantCode;
      this.roleId = row.id;
      this.roleUserName = row.name
      this.pageUser ={
        pageSize: 10,
        currentPage: 1,
        total: 0
      };
      this.searchUser = {};
      this.onLoadUser(this.pageUser);

      if (this.$refs.tableUser){
        this.$nextTick(()=>{
          this.$refs.tableUser.searchReset();
          this.$refs.tableUser.selectClear();
        })
      }
      this.userBox = true;

      let url = window.home_url + '/jpower-system/core/org/tree';
      if (this.$store.getters.isShowTenantCode){
        url = url + '?tenantCode='+row.tenantCode;
      }

      request.get(url).then((res) => {
        this.orgList = res.data.data;
      });
    },
    onLoadUser (page, params = {}) {
      this.userLoading = true;
      const values = {
        ...params,
        isEq: 'Y',
        pageNum: page.currentPage,
        pageSize: page.pageSize
      }
      this.listRole(values).then(res => {
        const data = res.data.data;
        this.pageUser.total = data.total;
        this.dataUser = data.records;
        this.userLoading = false;
      });
    },
    listRole(params = {}){
      const values = {
        ...params,
        roleId: this.roleId
      }
      if (this.$store.getters.isShowTenantCode){
        values.tenantCode_eq = this.tenantCode;
      }
      return listByRole(values);
    },
    roleUser(){
      this.pageRoleUser ={
        pageSize: 10,
        currentPage: 1,
        total: 0
      };
      this.searchRoleUser = {};
      this.onLoadRoleUser(this.pageRoleUser);

      if (this.$refs.tableRoleUser){
        this.$nextTick(()=>{
          this.$refs.tableRoleUser.searchReset();
          this.$refs.tableRoleUser.selectClear();
        })
      }

      this.roleUserBox = true;
    },
    onLoadRoleUser (page, params = {}) {
      this.roleUserLoading = true;

      const values = {
        ...params,
        isEq: 'N',
        pageNum: page.currentPage,
        pageSize: page.pageSize
      }
      this.listRole(values).then(res => {
        const data = res.data.data;
        this.pageRoleUser.total = data.total;
        this.dataRoleUser = data.records;
        this.roleUserLoading = false;
      });
    },
    searchChangeRoleUser (params, done) {
      this.pageRoleUser.currentPage = 1;
      this.onLoadRoleUser(this.pageRoleUser, params);
      done();
    },
    searchResetRoleUser () {
      this.pageRoleUser.currentPage = 1;
      this.onLoadRoleUser(this.pageRoleUser);
    },
    currentChangeRoleUser(currentPage) {
      this.pageRoleUser.currentPage = currentPage;
      this.onLoadRoleUser(this.pageRoleUser, this.searchRoleUser);
    },
    sizeChangeRoleUser (pageSize) {
      this.pageRoleUser.pageSize = pageSize;
      this.pageRoleUser.currentPage = 1;
      this.onLoadRoleUser(this.pageRoleUser, this.searchRoleUser);
    },
    addUser(){

      let ids = [];
      this.$refs.tableRoleUser.tableSelect.forEach(ele => {
        ids.push(ele.id);
      });

      if (ids.length <= 0){
        this.$message.warning('至少选择一条数据');
        return;
      }

      this.addUserLoading = true;

      addRoleUser({ roleId: this.roleId, userIds: ids.join(",") }).then((res)=>{
        if (res.data.status){
          this.onLoadUser(this.pageUser,this.searchUser);
          this.roleUserBox = false;
          this.$message.success('添加成功');
        }else {
          this.$message.error(res.data.message);
        }
        this.addUserLoading = false;
      }).catch(()=>{
        this.addUserLoading = false;
      });
    },
    deleteUser(){
      let ids = [];
      this.$refs.tableUser.tableSelect.forEach(ele => {
        ids.push(ele.id);
      });

      if (ids.length <= 0){
        this.$message.warning('至少选择一条数据');
        return;
      }

      this.$confirm(`确定去除所选用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.deleteUserLoading = true;

        deleteRoleUser({ roleId: this.roleId, userIds: ids.join(",") }).then((res)=>{
          if (res.data.status){
            this.pageUser.currentPage = 1;
            this.onLoadUser(this.pageUser,this.searchUser);
            this.$refs.tableUser.selectClear();
            this.$message.success('去除成功');
          }else {
            this.$message.error(res.data.message);
          }
          this.deleteUserLoading = false;
        }).catch(()=>{
          this.deleteUserLoading = false;
        });

      })

    },
    beforeOpen(done,type){
      if (["add"].includes(type)) {
        this.findObject(this.$refs.crud.option.column, 'tenantCode').value=this.$store.getters.tenantCode;
      }
      done();
    }
  }
}, {
  name: '/system/roleTree',
  res: (data) => {
    return {
      data: data.data
    }
  },
  crudPage: false
})
</script>

<style lang="scss">
.chilentTable .avue-crud > .avue-crud__menu {
  display: none!important;
}
.el-table__body tr.current-row>td {
  background: #94d8ec !important;
}
</style>
